package controller

import (
	"OceanLearn/common"
	"OceanLearn/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"OceanLearn/model"
	"golang.org/x/crypto/bcrypt"
	"log"
	"net/http"
	"github.com/jinzhu/gorm"
	_"github.com/go-sql-driver/mysql"
)

func Register(ctx *gin.Context) {
	DB :=common.GetDB()

	//获取参数
	name := ctx.PostForm("name")
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	//数据验证
	if len(telephone) != 11 {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422, "msg":"手机号必须为11位"})
		return
	}

	if len(password) < 6{
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422, "msg":"密码不能少于6位"})
		return
	}

	if len(name) == 0 {
		name = util.RandString(10)
		//name = RandString(10)
		//ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422, "msg":name})
		//return
	}
	log.Println(name,telephone,password)

	//判断手机号是否存在
	if isTelephoneExists(DB, telephone){
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422, "msg":"用户已经存在"})
		return
	}

	//创建用户
	//创建用户
	hasePassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":500, "msg":"加密失败"})
		return
	}
	newUser := model.User{
		Name: name,
		Telephone: telephone,
		Password: string(hasePassword),
	}
	DB.Create(&newUser)

	//返回结果
	ctx.JSON(200, gin.H{
		"code":200,
		"message": "注册成功",
	})
}

func Login(ctx *gin.Context)  {
	DB := common.GetDB()
	//获取数据
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")

	//数据验证
	fmt.Println(telephone, "手机号码长度", len(telephone))
	if len(telephone) != 11 {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422, "msg":"手机号必须为11位"})
		//ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422, "msg":len(telephone)})
		return
	}
	if len(password) < 6 {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422, "msg":"密码不能少于6位"})
		return
	}

	//判断手机号是否存在
	var user model.User
	DB.Where("telephone = ?", telephone).First(&user)
	if user.ID == 0 {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":400, "msg":"用户不存在"})
		return
	}

	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":400, "msg":"密码错误"})
		return
	}

	//发放token
	/*token, err := common.ReleaseToken(user)
	if err != nil {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":500, "msg":"系统异常"})
		log.Printf("token generate error: %v", err)
		return
	}*/
	token := 11

	//返回结果
	//response.Success(ctx, gin.H{"token": token}, "登录成功")
	ctx.JSON(http.StatusUnprocessableEntity,gin.H{
		"code":200,
		"data": gin.H{"token":token},
		"msg":"登录成功"})
}


func isTelephoneExists(db *gorm.DB, telephone string) bool {
	var user model.User
	db.Where("telephone = ?", telephone).First(&user)
	if user.ID != 0 {
		return true
	}
	return false
}

